package com.hy.utils;

import com.hy.config.constants.Constants;
import com.hy.config.constants.WeChatContant;
import com.hy.entitys.weChatInfo.ArticleItem;
import com.hy.entitys.weChatInfo.ReqMessage_Base;
import com.hy.entitys.weChatInfo.ReqMessage_Text;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
@SuppressWarnings("unchecked")
@Component
public class WxUtils {
    //日志
    private static final Logger log = LoggerFactory.getLogger(StoryUtils.class);


    //验证签名
    public static String check(String signature,String timestamp,String nonce,String echostr){
        String[] strs = new String [] {Constants.token,timestamp,nonce};
        Arrays.sort(strs);
        String str=strs[0]+strs[1]+strs[2];
        if(sha1(str).equals(signature)){
            return echostr;
        }
        return null;
    }
    //sha1加密
    private static String sha1(String str) {
        StringBuilder sb = new StringBuilder();
        try {
            char[] chars={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
            MessageDigest md = MessageDigest.getInstance("sha1");
            byte[] digest = md.digest(str.getBytes());

            for(byte b:digest){
                sb.append(chars[(b>>4)&15]);
                sb.append(chars[b&15]);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    //处理消息
    public static Map<String,String> parseXml(HttpServletRequest request){
        try {
            // 将解析结果存储在HashMap中
            Map<String,String> map = new HashMap<String,String>();

            // 从request中取得输入流
            InputStream inputStream = request.getInputStream();
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();
            // 遍历所有子节点
            for (Element e : elementList)
                map.put(e.getName(), e.getText());

            // 释放资源
            inputStream.close();
            inputStream = null;
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String mapToXML(Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        mapToXML2(map, sb);
        sb.append("</xml>");
        try {
            return sb.toString();
        } catch (Exception e) {
        }
        return null;
    }

    public static String entityToXML(Object o){
        XStream xStream = new XStream();
        xStream.processAnnotations(ReqMessage_Text.class);
        xStream.processAnnotations(ReqMessage_Base.class);
        return  xStream.toXML(o);
    }

    private static void mapToXML2(Map map, StringBuffer sb) {
        Set set = map.keySet();
        for (Iterator it = set.iterator(); it.hasNext();) {
            String key = (String) it.next();
            Object value = map.get(key);
            if (null == value)
                value = "";
            if (value.getClass().getName().equals("java.util.ArrayList")) {
                ArrayList list = (ArrayList) map.get(key);
                sb.append("<" + key + ">");
                for (int i = 0; i < list.size(); i++) {
                    HashMap hm = (HashMap) list.get(i);
                    mapToXML2(hm, sb);
                }
                sb.append("</" + key + ">");

            } else {
                if (value instanceof HashMap) {
                    sb.append("<" + key + ">");
                    mapToXML2((HashMap) value, sb);
                    sb.append("</" + key + ">");
                } else {
                    sb.append("<" + key + "><![CDATA[" + value + "]]></" + key + ">");
                }

            }

        }
    }
    /**
     * 回复文本消息
     * @param requestMap
     * @param content
     * @return
     */
    public static String sendTextMsg(Map<String,String> requestMap,String content){

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("ToUserName", requestMap.get(WeChatContant.FromUserName));
        map.put("FromUserName",  requestMap.get(WeChatContant.ToUserName));
        map.put("MsgType", WeChatContant.RESP_MESSAGE_TYPE_TEXT);
        map.put("CreateTime", new Date().getTime());
        map.put("Content", content);
        return  mapToXML(map);
    }

    /**
     * 回复图文消息
     * @param
     * @param items
     * @return
     */
    public static String sendMsg(ArticleItem articleItem,List<ArticleItem> items){
        if(items == null || items.size()<1){
            return "";
        }
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("ToUserName", articleItem.getToUserName());
        map.put("FromUserName", articleItem.getFromUserName());
        map.put("MsgType", "news");
        map.put("CreateTime", new Date().getTime());
        List<Map<String,Object>> Articles=new ArrayList<Map<String,Object>>();
        for(ArticleItem itembean : items){
            Map<String,Object> item=new HashMap<String, Object>();
            Map<String,Object> itemContent=new HashMap<String, Object>();
            itemContent.put("Title", itembean.getTitle());
            itemContent.put("Description", itembean.getDescription());
            itemContent.put("PicUrl", itembean.getPicUrl());
            itemContent.put("Url", itembean.getUrl());
            item.put("item",itemContent);
            Articles.add(item);
        }
        map.put("Articles", Articles);
        map.put("ArticleCount", Articles.size());
        return mapToXML(map);
    }
    //回复文本消息
    public static String sendMsg(ReqMessage_Text reqMessageText){

        if(reqMessageText == null){
            return "";
        }
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("ToUserName", reqMessageText.getToUserName());
        map.put("FromUserName", reqMessageText.getFromUserName());
        map.put("MsgType", "text");
        map.put("CreateTime", new Date().getTime());
        map.put("Content",reqMessageText.getContent());
        return mapToXML(map);
    }
}
